<template>
    <admin-container title="修改密码" :show-back="false">
        <el-form ref="form"
                 :model="form"
                 :rules="rules"
                 @submit.prevent.native="onSubmit">
            <el-form-item label="原密码" prop="old">
                <el-input v-model="form.old" type="password"/>
            </el-form-item>

            <el-form-item label="新密码" prop="pwd">
                <el-input v-model="form.pwd" type="password"/>
            </el-form-item>

            <el-form-item label="确认密码" prop="repwd">
                <el-input v-model="form.repwd" type="password"/>
            </el-form-item>

            <el-form-item>
                <el-button type="primary"
                           native-type="submit"
                           :loading="subing"
                >
                    确认修改
                </el-button>
            </el-form-item>
        </el-form>
    </admin-container>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';
import AdminContainer from '@/components/admin-container.vue';
import { changeAccountPassword } from '@/services/account.service';

type FormData = {
    old: string,
    pwd: string,
    repwd: string,
};

@Component({
    components: { AdminContainer }
})
export default class Password extends Vue {
    private form = {} as FormData;
    private subing: boolean = false;
    private rules: any = {
        old: [
            { required: true, message: '清输入原密码' }
        ],
        pwd: [
            { required: true, message: '清输入新密码' }
        ],
        repwd: [
            { required: true, message: '清确认新密码' }
        ],
    };

    mounted() {
    }

    // 提交修改
    async onSubmit() {
        await this.$validator('form');
        if (this.form.repwd !== this.form.pwd) {
            this.$message.error('二次密码不一致');
            return;
        }
        if (this.form.old === this.form.pwd) {
            this.$message.error('新旧密码不可统一');
            return;
        }
        this.subing = true;
        changeAccountPassword(this.form)
            .finally(() => {
                this.subing = false;
            })
            .then(() => {
                this.$message.success('密码修改成功');
            })
    }
}
</script>
